package com.liang.lollipop.lreader.service;

import android.accessibilityservice.AccessibilityService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.liang.lollipop.lreader.R;
import com.liang.lollipop.lreader.activity.SettingActivity;
import com.liang.lollipop.lreader.bean.AppInfo;
import com.liang.lollipop.lreader.bean.HistorBean;
import com.liang.lollipop.lreader.bean.ModelBean;
import com.liang.lollipop.lreader.util.AppInfoUtil;
import com.liang.lollipop.lreader.util.HistorDAO;
import com.liang.lollipop.lreader.util.ModelDAO;
import com.liang.lollipop.lreader.util.Settings;
import com.liang.lollipop.lreader.util.TaskUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lollipop on 2017/09/11.
 * 用于检测前台应用的服务
 */
public class DetectionService extends AccessibilityService{

    /*---------------------------应用跟随功能组件---------------------------*/
    //当前所有模式的bean
    private ArrayList<ModelBean> modelBeen = new ArrayList<>();
    //上一个包（用于在监听任务栈时，防止反复的判断）
    private String lastPackage = "";
    //
    private Handler handler = new Handler();
    //读取预设模式的工具类
    private ModelDAO modelDAO;
    //在添加页面
    private boolean onInstaller = false;
    //是否自动安装
    private boolean isAutoInstall = true;
    //是否自动打开
    private boolean isAutoOpen = true;
    //是否记录历史
    private boolean isHistoricalRecord = true;
    //是否记录详细的浏览历史
    private boolean isHistoricalRecordDetailed = true;
    //简易的时间格式化器
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
    //历史纪录的dao
    private HistorDAO historDAO;
    //应用列表
    private ArrayList<AppInfo> appInfos = new ArrayList<>();

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(SettingActivity.ACTION_SETTING_CHANGE)){
                initData();
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        modelDAO = new ModelDAO(this);
        historDAO = new HistorDAO(this);
        initData();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SettingActivity.ACTION_SETTING_CHANGE);
        registerReceiver(broadcastReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        modelDAO = null;
        modelBeen.clear();
        modelBeen = null;

        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        //当状态变化
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            //每次进入，直接为状态设置为否
            onInstaller = false;
            //获取当前包名
            String foregroundPackageName = event.getPackageName().toString();

            //记录历史
            recordHistory(foregroundPackageName,event.getClassName().toString());

            //如果包不是上一个包，那么认为应用更换了，那么更换为新的蒙版
            if(!lastPackage.equals(foregroundPackageName)){
                //如果这是新的窗口，那么就发起检查
                checkPackage(foregroundPackageName);
                lastPackage = foregroundPackageName;
            }
            //如果是安装应用页面
            if(foregroundPackageName.toLowerCase().contains("packageinstaller")){
                //那么就设置安装状态为是
                onInstaller = true;
                doInstall(event);
            }
        }
        //如果安装状态为是
        if(onInstaller){
            //执行再次选择安装
            doInstall(event);
        }

    }

    @Override
    public void onInterrupt() {

    }

    private void initData(){

        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<ArrayList<ModelBean>,ModelDAO>(handler) {
            @Override
            public void onUISuccess(ArrayList<ModelBean> result) {
                modelBeen.clear();
                if(result!=null)
                    modelBeen.addAll(result);
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
            }

            @Override
            public ArrayList<ModelBean> onBackground(ModelDAO[] args) throws Exception {
                ModelDAO dao = args[0];
                return dao.selectAll();
            }
        },modelDAO);

        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<ArrayList<AppInfo>, Context>(handler) {
            @Override
            public void onUISuccess(ArrayList<AppInfo> result) {
                appInfos.clear();
                if(result!=null)
                    appInfos.addAll(result);
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
                appInfos.clear();
            }

            @Override
            public ArrayList<AppInfo> onBackground(Context... args) throws Exception {
                return AppInfoUtil.queryAppInfoNoIntent(args[0]);
            }
        },this);

        isAutoInstall = Settings.isAutoInstall(this);
        isAutoOpen = Settings.isAutoOpen(this);
        isHistoricalRecord = Settings.isHistoricalRecord(this);
        isHistoricalRecordDetailed = Settings.isHistoricalRecordDetailed(this);
    }

    private void checkPackage(String newPackage){
        if(TextUtils.isEmpty(newPackage)){
            //如果没有新的包，那么跳过，并且将颜色转换为默认颜色
            sendBroadcast(new Intent(MaskingService.ACTION_FOREGROUND_CHANGE));
            return;
        }
        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<ModelBean,Object>(handler){

            @Override
            public void onUISuccess(ModelBean result) {
                Intent intent = new Intent(MaskingService.ACTION_FOREGROUND_CHANGE);
                if(result!=null){
                    intent.putExtra(MaskingService.ARG_COLOR,result.value);
                    intent.putExtra(MaskingService.ARG_ID,result.id);
                }
                sendBroadcast(intent);
            }

            @Override
            public void onUIError(Exception e, int code, String msg) {
                //如果出错了，那么跳转回默认的颜色
                sendBroadcast(new Intent(MaskingService.ACTION_FOREGROUND_CHANGE));
            }

            @Override
            public ModelBean onBackground(Object... args) throws Exception {
                String pkg = (String) args[0];
                ArrayList<ModelBean> been = (ArrayList<ModelBean>) args[1];
                for(ModelBean bean : been){
                    if(bean.project.equals(pkg)){
                        return bean;
                    }
                }
                return null;
            }
        },newPackage,modelBeen);
    }

    private void recordHistory(String pkg,String className){
        if(!isHistoricalRecord){
            return;
        }
        String name = "";
        if(!isHistoricalRecordDetailed && lastPackage.equals(pkg)){
            return;
        }
        if(isHistoricalRecordDetailed)
            name = className;

        TaskUtils.addTask(new TaskUtils.OnHandlerCallBack<Boolean,String>(handler) {
            @Override
            public void onUISuccess(Boolean result) {

            }

            @Override
            public void onUIError(Exception e, int code, String msg) {

            }

            @Override
            public Boolean onBackground(String[] args) throws Exception {
                String name = args[0];
                String pkg = args[1];

                for(AppInfo appInfo:appInfos){
                    if(appInfo.pkgName.equals(pkg)){
                        if(TextUtils.isEmpty(name)){
                            name = appInfo.name;
                        }else{
                            name = appInfo.name+":"+name;
                        }
                        break;
                    }
                }

                HistorBean bean = new HistorBean();
                bean.name = name;
                bean.pkg = pkg;
                bean.time = simpleDateFormat.format(new Date());
                historDAO.insert(bean);
                return true;
            }
        },name,pkg);

    }

    /**
     * 执行 安装 并打开应用
     */
    private void doInstall(AccessibilityEvent event) {
        if(!isAutoInstall)
            return;
        // source不为空
        boolean notNull = event.getSource() != null;
        if(!notNull)
            return;
        List<AccessibilityNodeInfo> intall_nodes = event.getSource()
                .findAccessibilityNodeInfosByText(getString(R.string.install));
        if (intall_nodes != null && !intall_nodes.isEmpty()) {
            AccessibilityNodeInfo node;
            for (int i = 0; i < intall_nodes.size(); i++) {
                node = intall_nodes.get(i);
                if (node.isEnabled()) {//不再检查按钮类型，将所有名字叫做“安装”的按钮点一遍
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
                //挨个回收了
                node.recycle();
            }

        }

        List<AccessibilityNodeInfo> next_nodes = event.getSource()
                .findAccessibilityNodeInfosByText(getString(R.string.next));
        if (next_nodes != null && !next_nodes.isEmpty()) {
            AccessibilityNodeInfo node;
            for (int i = 0; i < next_nodes.size(); i++) {
                node = next_nodes.get(i);
                //不再检查按钮类型，将所有名字叫做“下一步”的按钮点一遍
                if (node.isEnabled()) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
                //挨个回收了
                node.recycle();
            }
        }
        if(!isAutoOpen)
            return;
        List<AccessibilityNodeInfo> ok_nodes = event.getSource()
                .findAccessibilityNodeInfosByText(getString(R.string.open));
        if (ok_nodes != null && !ok_nodes.isEmpty()) {
            AccessibilityNodeInfo node;
            for (int i = 0; i < ok_nodes.size(); i++) {
                node = ok_nodes.get(i);
                Log.d("doInstall",node.getClassName().toString());
                //不再检查按钮类型，将所有名字叫做“打开”的按钮点一遍
                if (node.isEnabled()) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
                //挨个回收了
                node.recycle();
            }
        }
    }

}
